/**
 * @description  资产大类（资产配置）
 * @author zht
 */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, Spin, Tooltip } from 'antd';
import { SecondHeaderC, TableC, SunEchartsC } from '../../../comps';
import upRed from '../../../assets/commom/up_arrow_red.png';
import downGreen from '../../../assets/commom/down_arrow_green.png';
import ChartPie from './chartPie';
import accounting from 'accounting';
import _ from 'lodash';
import myStyle from './index.less';
import { getColumnIntoWidth } from "../../../utils/utils";
@Form.create()
class assetsBig extends PureComponent {
  constructor() {
    super();
    this.state = {
      columns: [],
      dataSource: [],
      pieData: [], //饼图数据
      currentPage: 1,
      numInPage: 1000,
    };
  }

  componentDidMount() {
    const { args } = this.props;
    this.getData(args);
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    const { args } = nextProps;

    if (JSON.stringify(args) !== JSON.stringify(this.props.args)) {
      this.getData(args);
    }
  }

  //获取数据
  getData = (args) => {
    const { currentPage, numInPage } = this.state;
    const { type } = this.props;
    const portfolioCode = args.portfolioCode
      ? {
          portfolioCode: args.portfolioCode,
        }
      : {
          portfolioCodeList: JSON.stringify(args.portfolioCodeList),
        };
    const datas = {
      ...portfolioCode,
      timeRange: args.timeRange,
      beginDate: args.beginDate,
      endDate: args.endDate,
      needPenetrate: args.needPenetrate,
      zqfz: args.zqfz,
    };
    this.props.dispatch({
      type: 'assetAllocationM/queryAssetsBig',
      payload: {
        ...datas,
        currentPage: currentPage,
        numInPage: numInPage,
      },
      callback: (data) => {
        if (data && data.dataSource.length && data.columns.length) {
          data.columns.map(item=>{
            if(item.key=='holdAmount'){
              item.title=type==1?item.title+'（元）':item.title+'（亿元）'
            }
            if(item.key=='holdAmountChange'){
              item.title=type==1?item.title+'（元）':item.title+'（万元）'
            }
          })
          data.dataSource.map(item=>{
            if(type==2){
              item.holdAmount=parseFloat((item.holdAmount||0)/100000000)
            }
          })
          const pieData = this.queryPieData(data.dataSource);
          const columnss = this.changeColumns(getColumnIntoWidth(data.columns,data.dataSource))
          const dataSources = this.changeDataSource(data.dataSource);
          this.setState({
            columns: columnss,
            dataSource: dataSources,
            pieData: pieData,
          });
        } else {
          this.setState({
            columns: [],
            dataSource: [],
            pieData: [],
          });
        }
      },
    });
  };

  //获取饼图数据
  queryPieData = (dataSource) => {
    let pieData = [];
    dataSource.map((item) => {
      const { assetType, holdRatio } = item;
      if (assetType !== '总计') {
        pieData.push({
          name: assetType,
          value: holdRatio?.toFixed(4),
        });
      }
    });
    return pieData.sort((a, b) => {
      return b.value - a.value;
    });
  };
  //改变表格钱数据样式
  changMoney = (data) => {
    if (data === null || data === undefined) {
      return '--';
    } else {
      if(this.props.type==2) data=parseFloat(Number(data)/10000)
      return accounting.formatNumber(Number(data), 2);
    }
  };

  //改变表格利率数据样式
  changRate = (data) => {
    if (data === null || data === undefined) {
      return '--';
    } else {
      if (isNaN(data)) {
        return data;
      } else {
        return (Number(data) * 100).toFixed(2) + '%';
      }
    }
  };

  //优化表格数据
  changeDataSource = (dataSource) => {
    const newDataSource = _.cloneDeep(dataSource);
    newDataSource.forEach((value) => {
      if (value.holdAmountChangeFlg == 'up') {
        value.holdAmountChange = (
          <div style={{ textAlign: 'right' }}>
            {' '}
            <span className={myStyle.cellUp}>{this.changMoney(value.holdAmountChange)}</span>
            <img style={{ width: '16px', height: '20px' }} src={upRed}></img>
          </div>
        );
      } else if (value.holdAmountChangeFlg == 'down') {
        value.holdAmountChange = (
          <div style={{ textAlign: 'right' }}>
            {' '}
            <span className={myStyle.cellDown}>{this.changMoney(value.holdAmountChange)}</span> <img style={{ width: '16px', height: '20px' }} src={downGreen}></img>
          </div>
        );
      } else {
        value.holdAmountChange = (
          <div style={{ textAlign: 'right' }}>
            {' '}
            <span className={myStyle.cell}>{this.changMoney(value.holdAmountChange)} -</span>
          </div>
        );
      }
      if (value.holdRatioChangeFlg == 'up') {
        value.holdRatioChange = (
          <div style={{ textAlign: 'right' }}>
            {' '}
            <span className={myStyle.cellUp}>{this.changRate(value.holdRatioChange)}</span> <img style={{ width: '16px', height: '20px' }} src={upRed}></img>
          </div>
        );
      } else if (value.holdRatioChangeFlg == 'down') {
        value.holdRatioChange = (
          <div style={{ textAlign: 'right' }}>
            {' '}
            <span className={myStyle.cellDown}>{this.changRate(value.holdRatioChange)}</span> <img style={{ width: '16px', height: '20px' }} src={downGreen}></img>
          </div>
        );
      } else {
        value.holdRatioChange = (
          <div style={{ textAlign: 'right' }}>
            {' '}
            <span className={myStyle.cell}>{this.changRate(value.holdRatioChange)} -</span>
          </div>
        );
      }
    });
    const compare = (key) => {
      return (obj1, obj2) => {
        // 降序
        var val1 = obj1[key];
        var val2 = obj2[key];
        if (val1 < val2) {
          return 1;
        } else if (val1 > val2) {
          return -1;
        } else {
          return 0;
        }
      };
    };
    const data = newDataSource[newDataSource.length - 1];
    newDataSource.pop();
    newDataSource.sort(compare('holdRatio'));
    newDataSource.push(data);

    return newDataSource;
  };

  //优化表格样式
  changeColumns = (columns) => {
    columns.forEach((value, index) => {
      if (value.key == 'holdRatio') {
        value['type'] = 'rate';
        // value['width'] = '90px';
      }
      if (value.key == 'holdAmount') {
        value['type'] = 'money';
        // value['width'] = '150px'
      }
      if (value.key == 'assetType') {
        // value['width'] = '87px';
      }

      if (value.key == 'holdAmountChange') {
        value.align='right';
        // value['width'] = '167px';
      }
      if (value.key == 'holdRatioChange') {
        value.title = (
          <div style={{ textAlign: 'right' }}>
            {' '}
            <span>{value.title}</span>
            <Tooltip title={<div>该类资产期初市值占比与期末市值占比之差</div>}>
              <QuestionCircleOutlined style={{ paddingLeft: '7px' }} />
            </Tooltip>
          </div>
        );
        value['width'] = '167px';
      }
    });
    return columns;
  };

  render() {
    const { pieData, columns, dataSource } = this.state;
    const { type }=this.props;
    return (
      <div>
        <Spin spinning={this.props.loading == true}>
          <SecondHeaderC title='资产大类' />
          <div className={type==1?myStyle.asset1:myStyle.asset2}>
            <div >
              <ChartPie data={pieData} height='300px' />
            </div>
            <div>
              <TableC
                columns={columns}
                dataSource={dataSource}
                rowKey="assetType"
                hidePage={true}
                scroll={{ y: 334 }}
              />
            </div>
          </div>
        </Spin>
      </div>
    );
  }
}
export default connect(({ assetAllocationM, loading }) => ({
  assetAllocationM,
  loading: loading.effects['assetAllocationM/queryAssetsBig'],
}))(assetsBig);
